import request from '@/utils/frontend/request'
import { message } from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import * as XLSX from 'xlsx'

interface UserForm {
	username: string
	nickname: string
	email: string
	gender: 'male' | 'female' | 'unknown'
}

export interface UserListItem extends UserForm {
	id: number
	status: string
	createdAt: string
	updatedAt: string
}

interface Pagination {
	current: number
	pageSize: number
	total: number
}

export function useUser() {
	const [loading, setLoading] = useState(false)
	const [userList, setUserList] = useState<UserListItem[]>([])
	const [messageApi, contextHolder] = message.useMessage()
	const [pagination, setPagination] = useState<Pagination>({
		current: 1,
		pageSize: 10,
		total: 0,
	})
	const [keyword, setKeyword] = useState('')

	// 获取用户列表
	const fetchUserList = async (
		page = pagination.current,
		size = pagination.pageSize,
		search = keyword
	) => {
		try {
			setLoading(true)
			const params = new URLSearchParams({
				page: String(page),
				size: String(size),
				keyword: search,
			})

			const { data } = (await request.get(`/user?${params}`)) as ApiResponse
			setUserList(data.list)
			setPagination((prev) => ({ ...prev, current: page, total: data.total }))
		} catch (errorMsg) {
			messageApi.error(errorMsg as string)
		} finally {
			setLoading(false)
		}
	}

	// 创建/更新用户
	const saveUser = async (values: UserForm, id?: number) => {
		try {
			if (id) {
				const { message } = (await request.patch(`/user/${id}`, values)) as ApiResponse

				return { message }
			}
			const { message } = (await request.post('/user', values)) as ApiResponse
			return { message }
		} catch (error) {
			console.error('Save user failed:', error)
			return { success: false, message: '操作失败' }
		}
	}

	// 删除用户
	const deleteUser = async (id: number) => {
		try {
			setLoading(true)
			const { message: msg } = (await request.delete(`/user/${id}`)) as ApiResponse
			messageApi.success(msg)

			// 如果当前页只有一条数据，删除后跳转到上一页
			if (userList.length === 1 && pagination.current > 1) {
				fetchUserList(pagination.current - 1, pagination.pageSize)
			} else {
				fetchUserList(pagination.current, pagination.pageSize)
			}
		} catch (errorMsg) {
			messageApi.error(errorMsg as string)
		} finally {
			setLoading(false)
		}
	}

	// 导出用户列表
	const exportUserList = async () => {
		try {
			setLoading(true)
			const { data } = (await request.get('/user/export')) as ApiResponse<UserListItem[]>

			const exportData = data.map((item: UserListItem) => ({
				用户名: item.username,
				昵称: item.nickname,
				邮箱: item.email,
				性别: item.gender === 'male' ? '男' : item.gender === 'female' ? '女' : '未知',
				状态: item.status === 'online' ? '在线' : '离线',
				创建时间: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
				更新时间: dayjs(item.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
			}))

			const wb = XLSX.utils.book_new()
			const ws = XLSX.utils.json_to_sheet(exportData)

			ws['!cols'] = [
				{ wch: 15 }, // 用户名
				{ wch: 15 }, // 昵称
				{ wch: 25 }, // 邮箱
				{ wch: 8 }, // 性别
				{ wch: 8 }, // 状态
				{ wch: 20 }, // 创建时间
				{ wch: 20 }, // 更新时间
			]

			XLSX.utils.book_append_sheet(wb, ws, '用户列表')
			XLSX.writeFile(wb, `用户列表_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`)
		} catch (errorMsg) {
			messageApi.error(errorMsg as string)
		} finally {
			setLoading(false)
		}
	}

	// 搜索
	const handleSearch = (value: string) => {
		setKeyword(value)
		fetchUserList(1, pagination.pageSize, value)
	}

	useEffect(() => {
		fetchUserList()
	}, [])

	return {
		loading,
		userList,
		pagination,
		setPagination,
		fetchUserList,
		saveUser,
		deleteUser,
		exportUserList,
		handleSearch,
		messageApi,
		contextHolder,
	}
}
